/*
 * Copyright (c) 2016 EEFUNG Software Co.Ltd. All rights reserved.
 * 版权所有(c)2016湖南蚁坊软件有限公司。保留所有权利。
 */

package com.zidian.leader.common.view;


import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;


import com.zidian.leader.R;
import com.zidian.leader.common.adapter.AdvancedRecyclerViewAdapter;
import com.zidian.leader.common.listener.OnAdvancedRecycleViewItemLongClickListener;
import com.zidian.leader.common.listener.OnAdvancedRecyclerViewItemListener;
import com.zidian.leader.common.listener.OnAdvancedRecyclerViewLoadMoreListener;
import com.zidian.leader.common.util.DensityUtils;
import com.zidian.leader.common.util.StringUtils;

import java.util.ArrayList;
import java.util.List;


/**
 * 自定义 RecyclerView
 * Created by Zuo Ji on 2015/7/24 0024.
 */
public class AdvancedRecyclerView<T> extends RelativeLayout {

    // recyclerview layout manager tag : linear 类似 ListView
    public static final String LAYOUT_MANAGER_LINEAR_TAG = "linear";

    // recyclerview layout manager tag : grid 类似 GridView
    public static final String LAYOUT_MANAGER_GRID_TAG = "grid";

    private SwipeRefreshLayout swipeRefreshLayout;

    private RecyclerView recyclerView;

    private int lastVisibleItem;

    private AdvancedRecyclerViewAdapter<T> adapter;

    private TextView emptyView;

    private boolean swiperefreshable;

    private String layoutManagerTag;

    private int numColumns;

    private boolean isLoadingMore = false;

    private ScrollListener scrollListener;

    /**
     * 为 RecyclerView 设置 Adapter
     *
     * @param adapter             适配器
     * @param onItemClickListener Item 点击监听
     * @param onLoadMoreListener  FooterView 点击监听
     */
    public void setAdapter(AdvancedRecyclerViewAdapter<T> adapter,
                           OnAdvancedRecyclerViewItemListener onItemClickListener,
                           OnAdvancedRecyclerViewLoadMoreListener onLoadMoreListener,
                           OnAdvancedRecycleViewItemLongClickListener onItemLongClickListener) {
        this.adapter = adapter;
        adapter.setOnItemClickListener(onItemClickListener);
        adapter.setOnLoadMoreListener(onLoadMoreListener);
        adapter.setOnItemLongClickListener(onItemLongClickListener);
        adapter.setRecyclerViewType(layoutManagerTag);
        recyclerView.setAdapter(adapter);

    }

    /**
     * 构造函数
     *
     * @param context 上下文
     * @param attrs   参数
     */
    public AdvancedRecyclerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        // 获取参数
        TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.advancedRecyclerView); // TypedArray是一个数组容器
        // 获取是否可以下拉刷新标志
        swiperefreshable = typedArray.getBoolean(R.styleable.advancedRecyclerView_swipe_refreshable, true);
        // 获取 layoutmanager 参数标志
        layoutManagerTag = typedArray.getString(R.styleable.advancedRecyclerView_layout_manager);
        // 获取网格时的列数
        numColumns = typedArray.getInt(R.styleable.advancedRecyclerView_numColumns, 0);
        if (!StringUtils.hasText(layoutManagerTag)) {
            layoutManagerTag = LAYOUT_MANAGER_LINEAR_TAG;
        }
        typedArray.recycle();

        init();
    }

    /**
     * 初始化
     */
    private void init() {
        // 设置 RecyclerView
        recyclerView = (RecyclerView) LayoutInflater.from(getContext()).inflate(R.layout.recycle_view_layout, null);
        // 设置 LayoutManager
        LinearLayoutManager layoutManager = null;
        GridLayoutManager gridLayoutManager = null;
        if (LAYOUT_MANAGER_GRID_TAG.equals(layoutManagerTag)) { // 非空判断 且为网格状态时设置 GridLayoutManager
            gridLayoutManager = new GridLayoutManager(getContext(), numColumns);
            gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                @Override
                public int getSpanSize(int position) {
                    switch (adapter.getItemViewType(position)) {
                        case AdvancedRecyclerViewAdapter.TYPE_ITEM:
                            return 1;
                        default:
                            return numColumns;
                    }
                }
            });
            recyclerView.setLayoutManager(gridLayoutManager);
        } else {
            layoutManager = new LinearLayoutManager(getContext());
            layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            recyclerView.setLayoutManager(layoutManager);
        }
        // 设置 RecyclerView 的滚动监听
        final LinearLayoutManager finalLayoutManager = layoutManager;
        final GridLayoutManager finalGridLayoutManager = gridLayoutManager;
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView,
                                             int newState) { // RecyclerView 滚动状态改变时调用
                super.onScrollStateChanged(recyclerView, newState);
                if (adapter != null && adapter.getData() != null && adapter.getData().size() > 0 && adapter.getOnLoadMoreListener() != null) { // adapter 非空判断, 加载更多监听 非空判断
                    if (!isLoadingMore && newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItem + 1 == adapter.getItemCount()) {
                        adapter.getOnLoadMoreListener().onLoadMore();
                    }
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) { // 滚动时调用
                super.onScrolled(recyclerView, dx, dy);
                if (scrollListener != null) {
                    scrollListener.onScroll(recyclerView, dx, dy);
                }
                if (finalLayoutManager != null) {
                    lastVisibleItem = finalLayoutManager.findLastVisibleItemPosition();
                } else {
                    lastVisibleItem = finalGridLayoutManager.findLastVisibleItemPosition();
                }
            }
        });

        if (swiperefreshable) { // 可下拉刷新
            // 设置 SwipeRefreshLayout
            swipeRefreshLayout = new SwipeRefreshLayout(getContext());
            swipeRefreshLayout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
            // 设置默认的刷新时 ProgressBar 的渐变颜色
            setRefreshLayoutProgressSchemeColorRes(R.color.colorPrimary);
            // 设置默认的刷新时 ProgressBar 的背景色
            setRefreshLayoutBGRes(R.color.colorPrimary);

            // 将 RecyclerView 添加到 SwipeRefreshLayout
            swipeRefreshLayout.addView(recyclerView);
            // 将 SwipeRefreshLayout
            addView(swipeRefreshLayout);
        } else { // 不可下拉刷新
            addView(recyclerView);
        }

        // 初始化空视图
        emptyView = new TextView(getContext());
        LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
        emptyView.setLayoutParams(layoutParams);
        emptyView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 17);
        emptyView.setTextColor(getResources().getColor(R.color.material_textBlack_disable));
        emptyView.setVisibility(View.GONE);
        emptyView.setGravity(Gravity.CENTER);
        // 将空视图添加到控件中显示
        addView(emptyView);
    }

    /**
     * 公开方法：设置 RecyclerView 显示分割线
     *
     * @param colorResId    分割线的颜色 Id
     * @param dividerHeight 分割线的宽度
     */
    public void setItemDividerColor(int colorResId, int dividerHeight) {
        recyclerView.addItemDecoration(new AdvancedRecyclerLinearDividerDecoration(getContext(), colorResId, dividerHeight));
    }

    /**
     * 公开方法：设置 RecyclerView GridView 显示分割线
     *
     * @param colorResId    分割线的颜色 Id
     * @param dividerHeight 分割线的宽度
     */
    public void setGridItemDividerColor(int colorResId, int dividerHeight) {
        recyclerView.addItemDecoration(new AdvancedRecyclerGridDividerDecoration(getContext(), colorResId, dividerHeight));
    }

    /**
     * 公开方法：显示没有加载到数据的视图
     *
     * @param text        文字
     * @param topDrawable 显示在文字上方的图片
     */
    public void showEmptyView(String text, Drawable topDrawable) {
        refreshData(new ArrayList<T>());
        emptyView.setVisibility(View.VISIBLE);
        emptyView.setText(text);
        if (topDrawable != null) {
            topDrawable.setBounds(0, 0, topDrawable.getMinimumWidth(), topDrawable.getMinimumHeight());
            emptyView.setCompoundDrawables(null, topDrawable, null, null);
            emptyView.setCompoundDrawablePadding(getResources().getDimensionPixelOffset(R.dimen.activity_horizontal_margin));
        }
    }


    /**
     * 重置 RecyclerView：将 RecyclerView 显示出来
     */
    public void resetRecyclerView() {
        if (emptyView.getVisibility() == View.VISIBLE) {
            emptyView.setVisibility(View.GONE);
        }
    }

    /**
     * 公开方法：设置刷新监听
     *
     * @param onRefreshListener 刷新监听
     */
    public void setOnRefreshListener(SwipeRefreshLayout.OnRefreshListener onRefreshListener) {
        if (swipeRefreshLayout != null) { // 非空判断
            swipeRefreshLayout.setOnRefreshListener(onRefreshListener);
        }
    }

    /**
     * 公开方法：设置刷新头布局的背景色
     *
     * @param resId 资源 Id
     */
    public void setRefreshLayoutBGRes(int resId) {
        if (swipeRefreshLayout != null) { // 非空判断
            swipeRefreshLayout.setProgressBackgroundColorSchemeResource(resId);
        }
    }

    /**
     * 公开方法：设置刷新头布局中 Progress 的渐变颜色
     *
     * @param resIds 资源 Ids
     */
    public void setRefreshLayoutProgressSchemeColorRes(int... resIds) {
        if (swipeRefreshLayout != null) { // 非空判断
            swipeRefreshLayout.setColorSchemeResources(resIds);
        }
    }

    /**
     * 公开方法：显示刷新等待
     */
    public void showRefresh() {
        if (swipeRefreshLayout != null) { // 非空判断
            swipeRefreshLayout.setRefreshing(true);
        }
    }

    /**
     * 公开方法：设置 SwipeRefreshLayout 的偏移量， 在RecyclerView 第一次调用刷新之前调用（否则不显示正在刷新动画）
     */
    public void beforeFirstOnRefresh() {
        if (swipeRefreshLayout != null) { // 非空判断
            swipeRefreshLayout.setProgressViewOffset(false, 0, DensityUtils.dip2px(getContext(), 24));
        }
    }

    /**
     * 公开方法：隐藏刷新等待
     */
    public void stopRefresh() {
        if (swipeRefreshLayout != null) { // 非空判断
            swipeRefreshLayout.setRefreshing(false);
        }
    }

    /**
     * 公开方法：列表滚动到指定的 position
     *
     * @param position 第一条看到的item 对应的 position
     */
    public void scrollToPosition(int position) {
        recyclerView.scrollToPosition(position);
    }

    /**
     * 公开方法：将刷新到的数据加载到列表中显示
     *
     * @param refreshData 刷新到的数据
     */
    public void refreshData(List<T> refreshData) {
        resetRecyclerView();
        if (refreshData != null && refreshData.size() != 0) {
            onLoadMoreTryAgain();
        }
        adapter.refreshData(refreshData);
    }

    /**
     * 公开方法：将加载更多获取到的数据加载到列表中显示
     *
     * @param loadMoreData 加载更多获取到的数据
     */
    public void loadMoreData(List<T> loadMoreData) {
        if (loadMoreData != null) {
            onLoadMoreTryAgain();
        }
        adapter.loadMoreData(loadMoreData);
    }

    /**
     * 公开方法：刷新某个 Item 视图
     *
     * @param position 需要刷新的位置
     */
    public void refreshItemView(int position) {
        adapter.refreshItemView(position);
    }

    /**
     * 公开方法：加载更多 没有加载到数据时调用
     */
    public void onLoadMoreNoData() {
        isLoadingMore = false;
        adapter.onLoadMoreNoData();
    }

    /**
     * 公开方法：加载更多 加载更多重试入口
     */
    public void onLoadMoreTryAgain() {
        isLoadingMore = false;
        adapter.onLoadMoreTryAgain();
    }

    /**
     * 公开方法：加载更多 加载更多
     */
    public void onLoadMoreWaiting() {
        isLoadingMore = true;
        adapter.onLoadMoreWaiting();
    }

    public void setScrollListener(ScrollListener scrollListener) {
        this.scrollListener = scrollListener;
    }

    public interface ScrollListener {
        void onScroll(RecyclerView recyclerView, int dx, int dy);
    }
}
